#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void Usage(const std::string& proc)
{
    std::cout << "\n\rUsage: " << proc << " server_ip, server_port\n" << std::endl;
}

// ./tcpclient server_ip server_port
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip = argv[1];
    u_int16_t server_port = std::stoi(argv[2]);

    // 2. 填充服务器的网络信息结构体
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);    // 将点分十进制的ip地址转换为网络字节序的ip地址

    /*客户端不需要“显式”地使用编码绑定，是系统"随机"地选择端口进行绑定
    客户端发起connect连接请求时，系统会自动选择一个端口进行绑定*/ 
    while(true)
    {
        int cnt = 5;
        bool isreconnect = false;
        // 1. 创建socket
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd < 0)
        {
            std::cerr << "socket error..." << std::endl;
            return 1;
        }
        do 
        {
            // 3. 客户端发起连接请求
            int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
            if(n < 0)
            {
                isreconnect = true;
                cnt--;
                std::cerr << "connect error..., reconnect: " << cnt << std::endl;
                close(sockfd);
                sleep(1);
            }
            else
            {
                break;
            }
        } while(cnt && isreconnect);

        if(cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            break;
        }

        // 4. 客户端与服务器端建立连接后，就可以进行通信了
        // while(true)
        // {
            std::string message;
            std::cout << "Please Enter# ";
            std::getline(std::cin, message);

            int n = write(sockfd, message.c_str(), message.size());
            if(n < 0)
            {
                std::cerr << "write error..." << std::endl;
                // break;
            }

            char inbuffer[4096];
            n = read(sockfd, inbuffer, sizeof(inbuffer));
            if(n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
            // else
            // {
            //     break;
            // }
        // }
    
        // 5. 关闭文件描述符
        close(sockfd);
    }
    
    return 0;
}